package com.search.controller;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.search.entity.Search;
import com.search.entity.SearchConfig;
import com.search.entity.SearchConfigEntity;
import com.search.service.imp.IndexUtil;
import com.search.util.JsonDateValueProcessor;
import com.search.util.PageUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import net.sf.json.JsonConfig;

@Controller
public class SearchIndexController {

	@Resource
	IndexUtil i;

	@Resource
	SearchConfig sc;

	@GetMapping(value = "/mkIndex")
	@ResponseBody
	public String mkIndex() {
		return i.mkIndex();
	}

	@GetMapping(value = "/delIndex")
	@ResponseBody
	public String delIndex() {
		return i.delIndex();
	}

	@GetMapping(value = "/search")
	public String search(HttpServletRequest request, Model model, @Validated Search search, BindingResult bindingResult,
			PageUtil page) {

		JSONObject jo = (JSONObject) JSONObject.fromObject(i.search(request, bindingResult, search, page));
		if ((boolean) jo.get("isSuccess")) {
			JSONObject rs = (JSONObject) jo.get("data");
			model.addAttribute("DATA", rs);
			return "search";
		} else {
			model.addAttribute("DATA", jo);
			return "searchError";
		}
	}

	@GetMapping(value = "/search1")
	@ResponseBody
	public String search1(HttpServletRequest request, Model model, @Valid Search search, BindingResult bindingResult,
			PageUtil page) {
		return i.search(request, bindingResult, search, page);
	}

	@GetMapping(value = "/searchArray")
	public String searchArray(Model model) {

		// 构造返回json
		JSONObject rs = new JSONObject();
		rs.put("data", null);
		rs.put("msg", "查询失败！");
		rs.put("isSuccess", false);

		// 检索分类查询
		List<SearchConfigEntity> list = sc.getSearchArray();
		if (list != null) {
			JsonConfig jsonConfig = new JsonConfig(); // 建立配置文件
			jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor("yyyy-MM-dd HH:mm:ss"));
			jsonConfig.setExcludes(new String[] { "user" });
			JSONArray jsonObject = (JSONArray) JSONSerializer.toJSON(list, jsonConfig);
			rs.put("msg", "查询成功！");
			rs.put("isSuccess", true);
			rs.put("data", jsonObject);
		} else {
			rs.put("msg", "查询成功，暂无统计信息！");
			rs.put("isSuccess", true);
		}
		model.addAttribute("DATA", rs);
		return "searchArray";
	}
}
